package com.ruoyi.common.utils.redis;

import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.common.utils.uuid.UUID;

@Component
public class redisUtil {
	private static Log log = LogFactory.getLog(redisUtil.class);

	private static RedisCache redisCache;

	@Autowired
	public redisUtil(RedisCache redisCache) {
		redisUtil.redisCache = redisCache;
	}

	public static final String GET_USERID_BYTOKEN = "loginToken:userId:%s";// 根据token获取用户id


	public static Object loginSaveAccessToken(Object userId, String accessToken) {
		try {

			int expire = (int) DateUtils.MILLIS_PER_DAY * 30;
			String tokenKey = String.format(GET_USERID_BYTOKEN, accessToken);
			String cacheObject = redisCache.getCacheObject(tokenKey);
			if (StringUtils.isBlank(cacheObject)) {
				// 登录时token过期刷新token
				accessToken = IdUtils.fastSimpleUUID();
				tokenKey = String.format(GET_USERID_BYTOKEN, accessToken);
			}
			/*
			 * 重置时间： userid 新token 新token userid
			 */
			redisCache.setCacheObject(tokenKey, userId, expire, TimeUnit.MINUTES);
			log.info("access_token==" + accessToken + "expires_in===" + expire);
			return userId;
		} catch (Exception e) {
			e.printStackTrace();
			return userId;
		}
	}

	public static void removeAccessToken(Object token) {

		String userIdKey = String.format(GET_USERID_BYTOKEN, token);
		redisCache.deleteObject(userIdKey);
	}

	public static String getUserIdBytoken(String token) {
		String key = String.format(GET_USERID_BYTOKEN, token);
		System.out.println("key:" + key);
		return redisCache.getCacheObject(key);
	}

	

}
